package com.xuzy.x808.server.clients;

import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.ConcurrentHashMap;

/**
 * todo 增加描述
 * 在设备连上时维护设备Id和ctx的关系，将来方便取用
 */
public class Connections {

    /**
     * 设备Id映射Ctx
     */
    private static ConcurrentHashMap<String, ChannelHandlerContext> devIdMapCtx = new ConcurrentHashMap();
    /**
     * channelId映射设备Id
     */
    private static ConcurrentHashMap<String, String> channelIdMapDevId = new ConcurrentHashMap();

    public static void addClient(String devId, ChannelHandlerContext ctx) {
        devIdMapCtx.put(devId, ctx);
        channelIdMapDevId.put(ctx.channel().id().toString(), devId);
    }

    public static void removeClient(String channelId) {
        String devId = getDevId(channelId);
        devIdMapCtx.remove(devId);
        channelIdMapDevId.remove(channelId);
    }

    public static ChannelHandlerContext getClient(String devId) {
        Object client = devIdMapCtx.get(devId);
        if (client == null)
            return null;
        return (ChannelHandlerContext) client;
    }

    public static String getDevId(String channelId) {
        Object devId = channelIdMapDevId.get(channelId);
        if (devId == null)
            return "";
        return devId.toString();
    }
}
